import { useEffect, useMemo, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import userApi from './api'
import { UserArr } from './interface'
import MyTable from '@/component/common/myTable'
import TableSelects, {
  SelectItem,
} from '@/component/common/tableSelects/tableSelects'
import {
  Button,
  DatePicker,
  Flex,
  Form,
  Input,
  Popconfirm,
  Radio,
  Select,
  Tag,
} from 'antd'
import { useMessageApi } from '@/component/context/messageContext/message'
import './index.scss'
import moment from 'moment'
import { MyForm, MyFormProps } from '@/component/common/myForm'
import { MyDrawer } from '@/component/common/myDrawer'
import { USER_AUTH, USER_SEX } from './config'
import RegionSelect from '@/component/common/regionSelect/regionSelect'

const columns: any = [
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    align: 'center',
  },
  {
    title: '权限',
    dataIndex: 'auth',
    key: 'auth',
    align: 'center',
    render: (_: any, { auth }: any) => <Tag>{auth}</Tag>,
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone',
    align: 'center',
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
    align: 'center',
  },
  {
    title: '出生日期',
    dataIndex: 'birth_day',
    key: 'birth_day',
    render: (text: string) => {
      return text?.slice(0, 10) || '/'
    },
    align: 'center',
  },
  {
    title: '户籍地区',
    dataIndex: 'home',
    key: 'home',
    align: 'center',
    render: (_: any, { home }: any) => (
      <RegionSelect onlyRead value={home}></RegionSelect>
    ),
  },
]

export interface User {
  name: string
  phone: string
  auth: string
  email: string
  password?: string
  sex: string
  birth_day: string
  home: string[] | string
}

function User() {
  const navigate = useNavigate()
  const messageApi = useMessageApi()
  const location = useLocation()
  const [userData, setUserData] = useState<UserArr>({
    users: [],
    total: 0,
  })
  const [searchParams, setSearchParams] = useState({
    pageNum: 1,
    pageSize: 20,
    name: '',
    phone: '',
    email: '',
  })
  const [loading, setLoading] = useState<boolean>(false)
  const [currentUser, setCurrentUser] = useState<User>({} as User)
  const [switchState, setSwitchState] = useState({
    isShowAdd: false,
    isShowEdit: false,
  })
  // 获取用户列表
  const getUsers = (params: any) => {
    setLoading(true)
    userApi.getUsers(params).then((res: any) => {
      res.users.forEach((element: any) => {
        element.key = element.id
      })
      setUserData(res)
      setTimeout(() => {
        setLoading(false)
      }, 300)
    })
  }
  // 删除用户
  const delUser = (ids: number[]) => {
    setLoading(true)
    userApi.delUsers(ids).then((data) => {
      getUsers(searchParams)
      messageApi.success(data)
      setSelectedRowKeys([])
      setTimeout(() => {
        setLoading(false)
      }, 300)
    })
  }

  useEffect(() => {
    const searchParams = new URLSearchParams(location.search)
    const params = {
      pageNum: searchParams.get('pageNum')
        ? Number(searchParams.get('pageNum'))
        : 1,
      pageSize: searchParams.get('pageSize')
        ? Number(searchParams.get('pageSize'))
        : 20,
      name: searchParams.get('name') ? String(searchParams.get('name')) : '',
      phone: searchParams.get('phone') ? String(searchParams.get('phone')) : '',
      email: searchParams.get('email') ? String(searchParams.get('email')) : '',
    }
    setSearchParams(params)
    getUsers(params)
  }, [location.search])

  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([])

  const tableOptions: SelectItem[] = [
    {
      render: (
        <Input
          key="name"
          placeholder="搜索姓名"
          value={searchParams.name}
          allowClear
          onChange={(e) => {
            setSearchParams((oldV) => {
              return { ...oldV, name: e.target.value }
            })
          }}
        />
      ),
    },
    {
      render: (
        <Input
          key="phone"
          placeholder="搜索手机号"
          value={searchParams.phone}
          allowClear
          onChange={(e) => {
            setSearchParams((oldV) => {
              return { ...oldV, phone: e.target.value }
            })
          }}
        />
      ),
    },
    {
      render: (
        <Input
          key="email"
          placeholder="搜索邮箱"
          value={searchParams.email}
          allowClear
          onChange={(e) => {
            setSearchParams((oldV) => {
              return { ...oldV, email: e.target.value }
            })
          }}
        />
      ),
    },
  ]

  // 添加用户弹窗组件
  const [addForm] = Form.useForm()
  const AddUserDrawer = () => {
    const addUserFormConf: MyFormProps = {
      name: 'addUserForm',
      form: addForm,
      conf: [
        {
          name: 'name',
          label: '用户名',
          content: <Input placeholder="请输入用户名" />,
          rules: [{ required: true }],
        },
        {
          name: 'auth',
          label: '权限',
          content: <Select placeholder="请选择" options={USER_AUTH} />,
          rules: [{ required: true }],
        },
        {
          name: 'phone',
          label: '手机号',
          content: <Input placeholder="请输入手机号" />,
          rules: [
            {
              required: true,
              pattern: /^1[3456789]\d{9}$/,
              message: '请输入正确的手机号',
            },
          ],
        },
        {
          name: 'password',
          label: '密码',
          content: <Input placeholder="请输入用户密码" />,
          rules: [{ required: true }],
        },
        {
          name: 'email',
          label: '邮箱',
          content: <Input placeholder="请输入邮箱" />,
          rules: [
            {
              required: true,
              pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
              message: '请输入正确的邮箱',
            },
          ],
        },
        {
          name: 'home',
          label: '户籍地',
          content: <RegionSelect></RegionSelect>,
          rules: [{ required: true }],
        },
        {
          name: 'birth_day',
          label: '出生日期',
          content: <DatePicker placeholder="请输入生日" />,
          rules: [{ required: true }],
        },
        {
          name: 'sex',
          label: '性别',
          content: (
            <Radio.Group>
              {USER_SEX.map((item) => {
                return (
                  <Radio key={item.value} value={item.value}>
                    {item.label}
                  </Radio>
                )
              })}
            </Radio.Group>
          ),
          rules: [{ required: true }],
        },
      ],
      onValuesChange: (changedValues, allValues) => {
        setCurrentUser(allValues)
      },
    }
    const addUser = () => {
      setLoading(true)
      userApi
        .addUser(currentUser)
        .then((data) => {
          messageApi.success(data)
          getUsers(searchParams)
          setSwitchState((oldV) => {
            return { ...oldV, isShowAdd: false }
          })
        })
        .finally(() => {
          setTimeout(() => {
            setLoading(false)
          }, 300)
        })
    }
    return (
      <MyDrawer
        open={switchState.isShowAdd}
        footer={
          <Flex gap={'1rem'} justify="right">
            <Button
              onClick={() =>
                setSwitchState((oldV) => {
                  return { ...oldV, isShowAdd: false }
                })
              }>
              取消
            </Button>
            <Button
              htmlType="submit"
              onClick={() => {
                addForm.validateFields().then(() => {
                  addUser()
                })
              }}>
              确定
            </Button>
          </Flex>
        }
        onClose={() =>
          setSwitchState((oldV) => {
            return { ...oldV, isShowAdd: false }
          })
        }>
        <MyForm {...addUserFormConf}></MyForm>
      </MyDrawer>
    )
  }

  // 编辑用户弹窗组件
  const [editForm] = Form.useForm()
  const EditUserDrawer = () => {
    const updateUser = () => {
      setLoading(true)
      userApi
        .updateUser(currentUser)
        .then((data) => {
          messageApi.success(data)
          getUsers(searchParams)
          setSwitchState((oldV) => {
            return { ...oldV, isShowEdit: false }
          })
        })
        .finally(() => {
          setTimeout(() => {
            setLoading(false)
          }, 300)
        })
    }
    const editUserFormConf: MyFormProps = {
      name: 'editUserForm',
      initialValues: {
        ...currentUser,
        birth_day: currentUser.birth_day ? moment(currentUser.birth_day) : null,
      },
      form: editForm,
      conf: [
        {
          name: 'name',
          label: '用户名',
          content: <Input placeholder="请输入用户名" />,
          rules: [{ required: true }],
        },
        {
          name: 'auth',
          label: '权限',
          content: <Select placeholder="请选择" options={USER_AUTH} />,
          rules: [{ required: true }],
        },
        {
          name: 'phone',
          label: '手机号',
          content: <Input placeholder="请输入手机号" />,
          rules: [
            {
              required: true,
              pattern: /^1[3456789]\d{9}$/,
              message: '请输入正确的手机号',
            },
          ],
        },
        {
          name: 'password',
          label: '密码',
          content: <Input placeholder="请输入用户密码" />,
          rules: [{ required: false }],
        },
        {
          name: 'email',
          label: '邮箱',
          content: <Input placeholder="请输入邮箱" />,
          rules: [
            {
              required: true,
              pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
              message: '请输入正确的邮箱',
            },
          ],
        },
        {
          name: 'home',
          label: '户籍地',
          content: <RegionSelect></RegionSelect>,
          rules: [{ required: true }],
        },
        {
          name: 'birth_day',
          label: '出生日期',
          content: <DatePicker placeholder="请输入生日" />,
          rules: [{ required: true }],
        },
        {
          name: 'sex',
          label: '性别',
          content: (
            <Radio.Group value={currentUser.sex}>
              {USER_SEX.map((item) => {
                return (
                  <Radio key={item.value} value={item.value}>
                    {item.label}
                  </Radio>
                )
              })}
            </Radio.Group>
          ),
          rules: [{ required: true }],
        },
      ],
      onValuesChange: (changedValues, allValues) => {
        setCurrentUser(allValues)
      },
    }
    return (
      <MyDrawer
        footer={
          <Flex gap={'1rem'} justify="right">
            <Button
              onClick={() => {
                setSwitchState((oldV) => {
                  return { ...oldV, isShowEdit: false }
                })
              }}>
              取消
            </Button>
            <Button
              htmlType="submit"
              onClick={() => {
                editForm.validateFields().then(() => {
                  updateUser()
                })
              }}>
              确定
            </Button>
          </Flex>
        }
        open={switchState.isShowEdit}
        onClose={() =>
          setSwitchState((oldV) => {
            return { ...oldV, isShowEdit: false }
          })
        }>
        <MyForm {...editUserFormConf}></MyForm>
      </MyDrawer>
    )
  }
  // 过滤器组件
  const Filter = () => {
    return (
      <TableSelects
        loading={loading}
        options={tableOptions}
        source={searchParams}
        onReset={() => {
          navigate({
            search: `?pageNum=1&pageSize=20`,
          })
        }}
        onSearch={() => {
          navigate({
            search: `?pageNum=${searchParams.pageNum}&pageSize=${searchParams.pageSize}&name=${searchParams.name}&phone=${searchParams.phone}&email=${searchParams.email}`,
          })
        }}
        buttonChildren={
          <Flex gap={'10px'}>
            {selectedRowKeys.length > 0 && (
              <Popconfirm
                title={`确定删除这 ${selectedRowKeys.length} 位用户吗？`}
                onConfirm={() => {
                  delUser(selectedRowKeys)
                }}>
                <Button>删除</Button>
              </Popconfirm>
            )}
            <Button
              onClick={() => {
                setSwitchState((oldV) => {
                  return { ...oldV, isShowAdd: true }
                })
              }}>
              添加
            </Button>
          </Flex>
        }></TableSelects>
    )
  }
  // 表格组件
  const Table = useMemo(() => {
    const rowSelection = {
      onChange: (selectedRowKeys: any) => {
        setSelectedRowKeys(selectedRowKeys)
      },
      getCheckboxProps: (record: any) => ({
        disabled: false,
      }),
    }
    return (
      <MyTable
        loading={loading}
        rowSelection={rowSelection}
        rowKey={(record) => record.id}
        dataSource={userData?.users}
        columns={columns}
        pageSize={searchParams.pageSize}
        total={userData.total}
        onPaginationChange={(pageNum, pageSize) => {
          navigate({
            search: `?pageNum=${pageNum}&pageSize=${pageSize}&name=${searchParams.name}&phone=${searchParams.phone}&email=${searchParams.email}`,
          })
        }}
        onRow={(record) => ({
          onClick: () => {
            editForm.setFieldsValue({
              ...record,
              birth_day: moment(record.birth_day?.slice(0, 10)) || null,
            })
            setSwitchState((oldV) => {
              return { ...oldV, isShowEdit: true }
            })
          },
        })}></MyTable>
    )
  }, [
    editForm,
    loading,
    navigate,
    searchParams.email,
    searchParams.name,
    searchParams.pageSize,
    searchParams.phone,
    userData.total,
    userData?.users,
  ])

  return (
    <div className="user">
      {AddUserDrawer()}
      {EditUserDrawer()}
      {Filter()}
      {Table}
    </div>
  )
}

export default User
